/**
 * 
 */
package com.point.business.database.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.point.business.util.Settings;

/**
 * @author Ilija Trajkoski
 * 
 */
public class DatabaseConnection {

	private static DatabaseConnection instance;
	private Connection connection;
	private static Logger logger = Logger.getLogger(DatabaseConnection.class);

	private DatabaseConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String server = Settings.getValue("database.server");
			String port = Settings.getValue("database.port");
			String dbName = Settings.getValue("database.name");
			String username = Settings.getValue("database.username");
			String password = Settings.getValue("database.password");
			setConnection(DriverManager.getConnection("jdbc:mysql://" + server
					+ ":" + port + "/" + dbName, username, password));
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public synchronized static DatabaseConnection getInstance() {
		if (instance == null) {
			instance = new DatabaseConnection();
		}
		return instance;
	}

	/**
	 * @return the connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * @param connection
	 *            the connection to set
	 */
	private void setConnection(Connection connection) {
		this.connection = connection;
	}

	/**
	 * @param statement
	 */
	public void closeStatement(PreparedStatement statement) {
		if (statement != null) {
			try {
				statement.close();
			} catch (SQLException e) {
				logger.error(e);
			}
		}
	}
}
